$(function () {
    // let div = document.querySelectorAll('.wrap ul li>div')
    let personal = document.querySelector('.userss')
    // let ul = document.querySelector('.good ul')
    // let dataid = sessionStorage.getItem('goodsId')

    $('.left span:first-child').click(function () {
        location.href = "./indexs.html"
    })
    let username = getCookie('username')
    if (username) {
        document.querySelector('.user').style.display = "block";
        document.querySelector('.user').innerHTML = `欢迎${getCookie('username')}来到vivo商城`
    } else {
        layer.msg("请先登录", {
            time: 8000
        })
        location.href = "./login.html"
    }

    //    console.log(div)
    // 给li鼠标移入移出事件
    $('.daohan .kou').hover(function (e) {
        // 鼠标移入。下拉显示
        let puts = e.target.getAttribute('index')
        // console.log(puts);
        $(this).parents().find('.wrap').stop().slideDown();
        // if (e.target.getAttribute('index') == 1) {
        switch (puts) {
            case '1':
                getLists();
                async function getLists() {
                    let res4 = await pAjax({
                        url: './severs/list.php',
                        data: {
                            pid: 11
                        },
                        dataType: 'json',
                    })

                    let data4 = res4.data;

                    let str4 = '';
                    data4.forEach(element => {
                        str4 += ` <div class="pos">
                    <div class="pos-1">
                        <img src="${element.imgpath.split('==========')[0]}" alt="">
                    </div>
                    <div class="pos-2">
                     ${element.introduce.split('==')[0]}
                    </div>
                 </div>`
                    });
                    document.querySelector('.put').innerHTML = str4;
                }
                break; //停止执行，跳出switch
            case '2':
                getListsd();
                async function getListsd() {
                    let res4 = await pAjax({
                        url: './severs/list.php',
                        data: {
                            pid: 12
                        },
                        dataType: 'json',
                    })

                    let data4 = res4.data;

                    let str4 = '';
                    data4.forEach(element => {
                        str4 += ` <div class="pos">
                    <div class="pos-1">
                        <img src="${element.imgpath.split('==========')[0]}" alt="">
                    </div>
                    <div class="pos-2">
                     ${element.introduce.split('==')[0]}
                    </div>
                 </div>`
                    });
                    document.querySelector('.put').innerHTML = str4;
                }
                // console.log("VIP会员");
                break; //停止执行，跳出switch
            case '3':
                getListsdl();
                async function getListsdl() {
                    let res4 = await pAjax({
                        url: './severs/list.php',
                        data: {
                            pid: 11
                        },
                        dataType: 'json',
                    })

                    let data4 = res4.data;

                    let str4 = '';
                    data4.forEach(element => {
                        str4 += ` <div class="pos">
                    <div class="pos-1">
                        <img src="${element.imgpath.split('==========')[0]}" alt="">
                    </div>
                    <div class="pos-2">
                     ${element.introduce.split('==')[0]}
                    </div>
                 </div>`
                    });
                    document.querySelector('.put').innerHTML = str4;
                }
                // console.log("管理员");
                break; //停止执行，跳出switch
            case '4':
                getListsdk();
                async function getListsdk() {
                    let res4 = await pAjax({
                        url: './severs/list.php',
                        data: {
                            pid: 12
                        },
                        dataType: 'json',
                    })

                    let data4 = res4.data;

                    let str4 = '';
                    data4.forEach(element => {
                        str4 += ` <div class="pos">
                    <div class="pos-1">
                        <img src="${element.imgpath.split('==========')[0]}" alt="">
                    </div>
                    <div class="pos-2">
                     ${element.introduce.split('==')[0]}
                    </div>
                 </div>`
                    });
                    document.querySelector('.put').innerHTML = str4;
                }
                // console.log("管理员");
                break; //停止执行，跳出switch
            case '5':
                getListsdb();
                async function getListsdb() {
                    let res4 = await pAjax({
                        url: './severs/list.php',
                        data: {
                            pid: 11
                        },
                        dataType: 'json',
                    })

                    let data4 = res4.data;

                    let str4 = '';
                    data4.forEach(element => {
                        str4 += ` <div class="pos">
                    <div class="pos-1">
                        <img src="${element.imgpath.split('==========')[0]}" alt="">
                    </div>
                    <div class="pos-2">
                     ${element.introduce.split('==')[0]}
                    </div>
                 </div>`
                    });
                    document.querySelector('.put').innerHTML = str4;
                }
                // console.log("管理员");
                break; //停止执行，跳出switch
            case '6':
                getListsdm();
                async function getListsdm() {
                    let res4 = await pAjax({
                        url: './severs/list.php',
                        data: {
                            pid: 12
                        },
                        dataType: 'json',
                    })

                    let data4 = res4.data;

                    let str4 = '';
                    data4.forEach(element => {
                        str4 += ` <div class="pos">
                    <div class="pos-1">
                        <img src="${element.imgpath.split('==========')[0]}" alt="">
                    </div>
                    <div class="pos-2">
                     ${element.introduce.split('==')[0]}
                    </div>
                 </div>`
                    });
                    document.querySelector('.put').innerHTML = str4;
                }
                // console.log("管理员");
                break; //停止执行，跳出switch
            case '7':
                getListsdp();
                async function getListsdp() {
                    let res4 = await pAjax({
                        url: './severs/list.php',
                        data: {
                            pid: 11
                        },
                        dataType: 'json',
                    })

                    let data4 = res4.data;

                    let str4 = '';
                    data4.forEach(element => {
                        str4 += ` <div class="pos">
                    <div class="pos-1">
                        <img src="${element.imgpath.split('==========')[0]}" alt="">
                    </div>
                    <div class="pos-2">
                     ${element.introduce.split('==')[0]}
                    </div>
                 </div>`
                    });
                    document.querySelector('.put').innerHTML = str4;
                }
                // console.log("管理员");
                break; //停止执行，跳出switch

            default: //上述条件都不满足时，默认执行的代码
                console.log("游客");
        }
        // }

    }, function () {
        // console.log("无敌1")
        $(this).parents().find('.wrap').stop().slideUp();
    })
    $('.wrap').hover(function () {
        $(this).parents().find('.wrap').stop().slideDown();
    }, function () {
        $(this).parents().find('.wrap').stop().slideUp();

    })
    personal.onclick = function () {
        delCookie('username')
        location.href = "./login.html"
    }
    $('.contiue').click(function () {
        location.href = "./paging.html"
    })
    ////////////////////////////////////
    //获取本地信息local
    let local = localStorage.getItem('data')
    let res = JSON.parse(local)
    // let but = $('.hou input').val();

    // 取出当前用户在购物车中的商品id
    let currId = res.map(v => {
        if (v.name === username) {
            return v.goodsid;
        }
    })
    // 去除goodsIds中的undefined,因为可能没有用户的数据
    let gids = currId.filter(v => v !== undefined);
    //   console.log(gids)
    let ids = gids.join(',');
    // console.log(ids)
    let nums = res.find(item => item.name === username);
    // v.name ===username
    // console.log(nums)
    // console.log(pan)
    if (nums) {
        cartGood();
        // console.log(8)
    } else {
        $('.tei').html(`<div class="replace">
        <div class="notop">
            <img src="./images/no-result.50507a32.png" alt="">
        </div>
        <p>
                哎呀，购物车为空!
        </p>
        <div class="noend">
            <input type="button" value="去选购逛逛">
        </div>

    </div>`)
        $('.noend input').click(function () {
            location.href = "./paging.html"
        })
    }
    ////////////////////////////////////

    async function cartGood() {
        let res4 = await pAjax({
            url: './severs/shopping.php',
            data: {
                ids
            },
            dataType: 'json',
        })

        // console.log(res4)
        let data4 = res4.data;
        // console.log(data4)
        let str4 = '';
        data4.forEach(element => {
            let nums = res.find(item => item.name === username && item.goodsid === element.id).sum;
            str4 += `       <div class="shopping">
            <div class="shopping-con">
                <div class="table-two">
                    <table>
                        <tbody>
                            <tr>
                                <td class="gast">
                                    <input type="checkbox">
                                </td>
                                <td class="gast-1">
                                    <img src="${element.imgpath.split('==========')[0]}" alt="">
                                </td>
                                <td>
                                    <p class="gast-2">
                                        <span>
                                            ${element.name}
                                        </span>
                                        <span>
                                            颜色:白色
                                        </span>
                                    </p>
                                </td>
                                <td>
                                    ${element.price}
                                </td>
                                <td class="hou">
                                    <a href="javascript:;" class="jian"><i class="iconfont icon-jian"></i></a>
                                    <input type="button" value="${nums}" data-stock="${element.stock}" data-id="${element.id}">
                                    <a href="javascript:;" class="adds"><i class="iconfont icon-jiahao_o"></i></a>
                                </td>
                                <td class="smu">
                                    ${element.price*nums}
                                </td>
                                <td class="del">
                                    删除
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="tuo">
                        <span>[赠品] :<i class="iconfont icon-jifenguizeguankong2"></i>购物送积分</span>
                    </div>
                </div>
            </div>
        </div>`
        });
        document.querySelector('.tei').innerHTML = str4;
        jian();
        end();
        delet();
    }

    function jian() {
        $('.jian').click(function () {
            let res = $(this).next().val() - 0
            if (res == 1) {
                $(this).next().val(1)
                return false;
            }
            $(this).next().val(--res)

            // *element.price)
            let jiaguo = $(this).next().val() - 0
            let shang = $(this).parent().prev().text() - 0
            let ji = jiaguo * shang
            $(this).parent().parent().find('.smu').text(ji)
            ///
            let useid = $(this).next()[0].dataset.id
            let dataL = JSON.parse(localStorage.getItem('data'))
            let dataJson = dataL.find(v => v.name === username && v.goodsid === useid);
            dataJson.sum = jiaguo;
            localStorage.setItem('data', JSON.stringify(dataL))
            numAll();
        })
        $('.adds').click(function () {
            let stock = $('.hou input')[0].dataset.stock
            let res = $(this).prev().val()
            if (res == stock) {
                $(this).prev().val(stock)
                layer.msg("已达最大库存")
                return false;
            }
            $(this).prev().val(++res)
            let jiaguo = $(this).prev().val() - 0
            let shang = $(this).parent().prev().text() - 0
            let ji = jiaguo * shang
            $(this).parent().parent().find('.smu').text(ji)
            ////
            let useid = $(this).prev()[0].dataset.id
            let dataL = JSON.parse(localStorage.getItem('data'))
            let dataJson = dataL.find(v => v.name === username && v.goodsid === useid);
            dataJson.sum = jiaguo;
            localStorage.setItem('data', JSON.stringify(dataL))
            numAll();
        })

    }
    //计算商品总价
    function numAll() {
        let totalNum = 0;
        let totalPrice = 0;
        $('.gast input').each((i, v) => {
            if ($(v).prop('checked')) {
                totalNum += $(v).parent().parent().find('.hou').find('input').val() - 0;
                totalPrice += $(v).parent().parent().find('.smu').text() - 0;
            }
        })
        $('.sos').text(totalNum);
        $('.prps').text(totalPrice);
    }
    //全选单选
    function end() {
        $('.confirm').click(function () {
            $('.confirm').prop('checked', $(this).prop('checked'));
            $('.gast input').prop('checked', $(this).prop('checked'));
            numAll();
        })
        $('.gast input').click(function () {
            let inps = Array.prototype.slice.call($('.gast input'));
            let flag = inps.every(v => $(v).prop('checked'));
            $('.confirm').prop('checked', flag);
            numAll();
        })
    }
    //单独删除和批量删除
    function delet() {
        //单独删除
        $('.del').click(function () {
            $(this).parent().parent().parent().parent().parent().parent().remove()
            let id = $(this).prev().prev().find('input')[0].dataset.id
            let data = JSON.parse(localStorage.getItem('data'));
            let dataArr = data.filter(v => {
                return !(v.name === username && v.goodsid === id)
            })
            localStorage.setItem('data', JSON.stringify(dataArr));
            let index = dataArr.findIndex(v => v.name === username);
            if (index == -1) {
                $('.tei').html(`<div class="replace">
               <div class="notop">
                   <img src="./images/no-result.50507a32.png" alt="">
               </div>
               <p>
                       哎呀，购物车为空!
               </p>
               <div class="noend">
                   <input type="button" value="去选购逛逛">
               </div>
   
           </div>`)
                $('.noend input').click(function () {
                    location.href = "./paging.html"
                })
            } else {
                layer.msg("删除成功", {
                    time: 1000
                })
            }

        })
    }
    $('.select-right button').click(function () {
        location.href = "./buy.html"
    })
})